<?php

declare(strict_types=1);
/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-11-05 13:43:31
 * @Last Modified time: 2023-02-07 16:11:43
 */
namespace frank\base;

use think\App;
use think\facade\Config;
use think\facade\Db;
use think\Container;
use frank\base\BaseController;

abstract class BaseService
{

     /**
     * 应用实例
     * @var App
     */
    protected $app;

     /**
     * 模型注入
     * @var object
     */
    protected $dao;


    // 错误信息
    protected $error;

    /**
     * Service constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->initialize();
    }

    /**
     * 初始化服务
     * @return $this
     */
    protected function initialize()
    {
        return $this;
    }

    /**
     * 静态实例对象
     * @param array $args
     * @return static
     */
    public static function instance(...$args)
    {
        return Container::getInstance()->make(static::class, $args);
    }

    /**
     * 魔术函数
     */
    public function __call($name, $arguments)
    {
        if (method_exists($this->dao, $name)) {
            return call_user_func_array([$this->dao, $name], $arguments);
        }
        throw new \BadMethodCallException('Call to undefined method ' . get_class($this->dao) . '::' . $name . '()');
    }

    /**
     * 获取错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 是否存在错误
     * @return bool
     */
    public function hasError()
    {
        return !empty($this->error);
    }

    /**
     * 设置错误信息
     * @param $error
     */
    public function setError($error)
    {
        empty($this->error) && $this->error = $error;
    }

    /**
     * 获取分页配置
     */
    public function getPageValue(bool $isPage = true, bool $isRelieve = true)
    {
        $page = $limit = 0;
        if ($isPage) {
            $page = app()->request->param(Config::get('database.page.pageKey', 'page') . '/d', 0);
            $limit = app()->request->param(Config::get('database.page.limitKey', 'limit') . '/d', 0);
        }
        $limitMax = Config::get('database.page.limitMax');
        $defaultLimit = Config::get('database.page.defaultLimit', 10);
        if ($limit > $limitMax && $isRelieve) {
            $limit = $limitMax;
        }
        return [(int)$page, (int)$limit, (int)$defaultLimit];
    }

    /**
     * 密码hash加密
     */
    public function passwordHash(string $password)
    {
        return password_hash($password, PASSWORD_BCRYPT);
    }

    /**
     * 数据库事务操作
     */
    public function transaction(callable $closure, bool $isTran = true)
    {
        return $isTran ? Db::transaction($closure) : $closure();
    }
}